import React, { useState } from 'react'
import { useHistory } from 'react-router-dom'
import {
  Paper,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Collapse,
} from '@material-ui/core'
import {
  Drafts as DraftsIcon,
  Inbox as InboxIcon,
  StarBorder,
  ExpandLess,
  ExpandMore,
} from '@material-ui/icons'
import styled from 'styled-components'

const StyledListItem = styled(
  ({ isNested, ...rest }) => <ListItem {...rest} />
)`
  padding-left: ${props => props.isNested ? '32px !important' : '0'};
`

interface Props {
  visible: boolean;
  className: string;
  config: object[];
}

const Menu: React.FC<Props> = (props) => {
  const { config } = props
  const history = useHistory()

  function generateConfig (config) {
    return config.map(item => {
      if (item.children) {
        return { ...item, open: false }
      }
      return item
    })
  }

  const [configState, setConfigState] = useState(() => generateConfig(config))

  function handleMenuItemClick (item, idx: number): void {
    if (item.children) {
      configState[idx].open = !configState[idx].open
      setConfigState(JSON.parse(JSON.stringify(configState)))
    } else {
      //TODO: click
      history.push(item.path)
    }

  }


  const renderMenuItem = (config, nested = false) => {

    const renderListItem = (item, idx) => {
      return (
        <StyledListItem isNested={nested} onClick={() => handleMenuItemClick(item, idx)} button>
          <ListItemIcon>
            <DraftsIcon />
          </ListItemIcon>
          <ListItemText primary={item.title} />
          {item.children && (item.open ? <ExpandLess /> : <ExpandMore />)}
        </StyledListItem>
      )
    }

    return config.map((item, idx) => {
      return (
        <React.Fragment key={item.path}>
          {renderListItem(item, idx)}
          {item.children && item.open && (
            <Collapse in={true} timeout="auto" unmountOnExit>
              <List component="div" disablePadding>
                {renderMenuItem(item.children, true)}
              </List>
            </Collapse>
          )}
        </React.Fragment>
      )
    })
  }

  return props.visible ? (
    <Paper className={props.className} square>
      <List
        component="nav"
      >
       {renderMenuItem(configState)}
      </List>
    </Paper>
  ) : null
}

export default Menu
